package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> findAll() {
        return categoryMapper.findAll();
    }

    @Override
    public void updateCategory(Category category) {
//        //设置更改的变量时间和修改人
//        category.setUpdateUser(1L);
//        category.setUpdateTime(new Date());
        //调用mapper对象更新对象
        categoryMapper.gengxin(category);
        //categoryMapper.updateById(category);
    }

    @Override
    public ResultInfo deleteCateGory(Long id) {
        //1.首先通过id查找是否有
        int countFromDish = categoryMapper.countDishByCategoryId(id);
        //2.判断并返回一个对象
        if (countFromDish > 0){
            //返回一个错误对象
            //return ResultInfo.error("当前分类下存在菜品,不能删除");
            throw new CustomException("当前分类下存在菜品,不能删除");//自己抛出异常
        }
        //3.首先通过id查找是否有
        int countFromSetMeal = categoryMapper.countSetMealByCategoryId(id);
        //4.判断并返回一个对象
        if (countFromSetMeal > 0){
            //返回一个错误对象
            //return ResultInfo.error("当前分类下存在套餐,不能删除");
            throw new CustomException("当前分类下存在套餐,不能删除");//自己抛出异常
        }
        //5.通过上面两个判断之后进行删除并返回一个成功ResultInfo对象
        categoryMapper.deleteCategory(id);
        return ResultInfo.success(null);
    }

    @Override
    public void addCategory(Category category) {
        //设置未填写的变量
        //1.id
        category.setId(IdUtil.createSnowflake(1,1).nextId());
        //创建时间和更新时间
//        Date date = new Date();
//        category.setCreateTime(date);
//        category.setUpdateTime(date);
//        //创建人和更新人员
//        category.setCreateUser(1L);
//        category.setUpdateUser(1L);
        //将设置好的对象交给mapper对象保存
        categoryMapper.addCategory(category);
    }


    @Override
    public List<Category> findCategoryList(Integer type) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getType,type);
        List<Category> categoryList = categoryMapper.selectList(wrapper);

        return categoryList;
    }
}
